package com.roger.tool.utils;

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.text.TextUtils;

/**
 * @author lch
 * @version Create time：2017-9-25
 * @类说明：
 */
public class MetaInfReader {

	private static String debugEnable = null;

	/**
	 * 读取APK META-INF 下的文件名称，可以用于处理Debug开关；默认false，如放入 “debugEnable_true” 名称的空文件，则返回true
	 * @param context
	 * @return
	 */
	public static String getDebugEnable(Context context) {
		if (debugEnable != null) {
			return debugEnable;
		}

		long startTime = System.currentTimeMillis();

		final String start_flag = "META-INF/debugEnable_";
		ApplicationInfo appinfo = context.getApplicationInfo();

		if (appinfo != null) {
			String sourceDir = appinfo.sourceDir;
			if (sourceDir != null) {
				ZipFile zipfile = null;
				try {
					zipfile = new ZipFile(sourceDir);
					Enumeration<?> entries = zipfile.entries();
					while (entries.hasMoreElements()) {
						ZipEntry entry = ((ZipEntry) entries.nextElement());
						String entryName = entry.getName();
						if (entryName.contains(start_flag)) {
							debugEnable = entryName.replace(start_flag, "");
							break;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (zipfile != null) {
						try {
							zipfile.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}

		}

		if (TextUtils.isEmpty(debugEnable)) {
			debugEnable = "false";// 读不到渠道号就默认
		}

		long delta = System.currentTimeMillis() - startTime;

		System.out.println("Reader metaInf deltaTime : " + delta);

		return debugEnable;
	}

}
